#include "TimeManager.h"
#include "Timer.h"
#include <algorithm>

namespace sol9
{
namespace util
{

	LONGLONG TimeManager::s_nFrequency;
	LONGLONG TimeManager::s_nPrevTime;
	TimerList TimeManager::s_listTimers;

	bool TimeManager::initialize()
	{
		LARGE_INTEGER f;
		QueryPerformanceFrequency(&f);
		s_nFrequency = f.QuadPart;

		LARGE_INTEGER p;
		QueryPerformanceCounter(&p);
		s_nPrevTime = p.QuadPart;
		return true;
	}

	void TimeManager::tickTimers()
	{
		auto tick = [](Timer* timer)
		{
			if (timer->isWorked())
				timer->_tick();
		};

		std::for_each(s_listTimers.begin(), s_listTimers.end(), tick);
	}

	LONGLONG TimeManager::getTime64()
	{
		LARGE_INTEGER t;
		QueryPerformanceCounter(&t);
		return (LONGLONG)t.QuadPart;
	}

	u32 TimeManager::getTime32()
	{
		return GetTickCount();
	}

	u32 TimeManager::getTick()
	{
		LONGLONG curr = getTime64();
		LONGLONG delta = curr - s_nPrevTime;
		s_nPrevTime = curr;

		u32 tick = (u32)(delta * 1000 / s_nFrequency);
		return tick;
	}

} // namespace util
} // namespace sol9